package ywh.utils
{
	
	/**
	 * 数组工具类，静态方法类;
	 * @author 杨伟华
	 * @version 1.0
	 * 
	 * Created 1/15/2013 11:32 PM
	 */
	public class ArrayUtils
	{
		/**
		 * 随机排序数组;
		 * @param	array
		 * @return 
		 */
		static public function randomizeArray(array:Array):Array
		{
			var newArray:Array = new Array();
			while (array.length > 0)
			{
				newArray.push(array.splice(Math.floor(Math.random() * array.length), 1));
			}
			return newArray;
		}
		/**
		 * 寻找临界值的序号，二分法;
		 * 示例：
		 * var arr1:Array = [1,7,7,11,11,11,11,25,190];
		 * trace(getValueItemIndex(arr1,11,1)); 返回6;
		 * trace(getValueItemIndex(arr1,11,-1));返回3;
		 * 
		 * @param	arr	目标数组
		 * @param	value 目标数值
		 * @param	toMin 如果前值有多个相等，如何处理;1，向左查找；0；不动;-1;向右查找;
		 * @param	prop	搜索字段，当prop为null的时候，数组元素为数字;
		 * @param	startIndex	起始序号;
		 * @param	endIndex	结束序号;
		 * @return  查询
		 */
		static public function getItemIndexBySort(arr:Array, value:Number, toMin:int, prop:String = null, startIndex:int = -1, endIndex:int = -1):int
		{
			if (endIndex < 0)
			{
				startIndex = 0;
				endIndex = arr.length - 1;
			}
			var tempIndex:int;
			var tempValue:Number;
			var middleIndex:uint = Math.floor((startIndex + endIndex + 1) / 2);
			var middleItem:Object = arr[middleIndex];
			var middleValue:Number = (prop == null) ? Number(middleItem) : Number(middleItem[prop]);
			if (middleValue == value)
			{
				tempIndex = middleIndex;
			}
			else
			{
				if (middleValue > value)
				{
					endIndex = middleIndex - 1;
				}
				else
				{
					startIndex = middleIndex;
				}
				if (endIndex == startIndex)
				{
					tempIndex = startIndex;
				}
				else
				{
					return arguments.callee(arr, value, toMin, prop, startIndex, endIndex);
				}
			}
			
			if (toMin != 0)
			{
				var al:uint = arr.length;
				var pv:Number;
				tempValue = (prop == null) ? Number(arr[tempIndex]) : Number(arr[tempIndex][prop]);
				for (tempIndex += toMin; tempIndex > 0 && tempIndex < al; tempIndex += toMin)
				{
					pv = (prop == null) ? Number(arr[tempIndex]):Number(arr[tempIndex][prop]);
					if (tempValue != pv)
					{
						tempIndex -=  toMin;
						break;
					}
				}
			}
			return tempIndex;
		}
		
	}
}
